package com.bilubi.reggie.reggie.controller;

import com.bilubi.reggie.reggie.property.PathProperties;
import com.bilubi.reggie.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping(value = "/common")
public class CommonController {

    @Autowired
    PathProperties pathProperties;

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<byte[]> downloadFile(@RequestParam(value = "name") String name) throws IOException {
        String filePath = pathProperties.getFilepath() + "/" + name;
        Resource resource = new FileSystemResource(filePath);
        if (resource.exists()) {
            File file = resource.getFile();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            headers.setContentDispositionFormData("attachment", file.getName());
            return new ResponseEntity<>(Files.readAllBytes(file.toPath()), headers, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public R<String> fileUp(@RequestParam("file") MultipartFile file) throws IOException {
        String dirPath = pathProperties.getFilepath();
        File dirFile = new File(dirPath);
        String fileName = null;
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        else {
            BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
            fileName = UUID.randomUUID() + Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().indexOf("."));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dirPath + "/" + fileName));
            byte[] buffer = new byte[1024];
            int readCount = 0;
            while((readCount=bis.read(buffer))!=-1)
                bos.write(buffer, 0, readCount);
            bos.flush();
            bos.close();
            bis.close();
        }
        return R.success(fileName);
    }

}
